#include <cJSON.h>
#include <stdlib.h>
#include <signal.h>
#include <debug_printf.h>
#include "PahoMqttClient.h"
#include "MqInvoker.h"
#include "local_error.h"

#define ADDRESS     "tcp://localhost:1883"
#define CLIENTID    "ExampleClientPub"
#define TOPIC       "test_paho"
#define USERNAME    "user"
#define PASSWORD    "password"

using namespace smq;
using namespace thmar;
MqInvoker* invoker;
/* 程序退出时执行的函数 */ 
void cleanup() {
    printf("Program exiting, cleaning up...\n");
    if(invoker)
    {
        printf("Stopping client...\n");
        invoker->stop();
        delete invoker;
        invoker = NULL;
    }
}
/* 自定义的信号处理函数 */ 
void handle_sigint(int sig) {
    printf("Catch Ctrl-C, exit program.\n");
    exit(0);
}
void invokeResponse(const cJSON* response){

}
/* MqINvoker 调用测试 */
int main(int argc, char* argv[]) {
    dbg_set_debuglog(true);
    printf("MQInvokerTest: addDevice");
    // 注册退出时执行的函数
    if (atexit(cleanup) != 0) {
        fprintf(stderr,"failed to register cleanup function, exiting...\n");
        exit(1);
    }
    /* 注册信号处理函数 */ 
    signal(SIGINT, handle_sigint);
    ThmarMqttClient* mqttClient = new PahoMqttClient(ADDRESS, USERNAME, PASSWORD,CLIENTID);
    MqInvoker_options options = MqInvoker_options_initializer;
    /** 要求服务端如果调用异常，只返回简单异常信息 */
    options.thinError = true;
    invoker = new MqInvoker(mqttClient, options);
    int code = invoker->start();
    if(code!= 0)
    {
        printf("start failed, code: %d\n", code);
        thmar_print_local_err();
        return -1;
    }

    /* 构造调用参数 */
    const char* json = "{\"deviceBean\":{\"bol\":true,\"addressType\":\"MAC\",\"model\":\"M0\",\"name\":\"HELLO\",\"physicalAddress\":\"7070707070\"},\"tokenId\":\"TOKEN:1f470a2a820202a8\"}";
    cJSON* args = cJSON_Parse(json);
    /* 保存调用结果 */
    cJSON* result = nullptr;
    /* 调用getDevice接口 */ 
    code = invoker->syncCall("IDeviceCenter", "addDevice", args, &result);
    cJSON_Delete(args);
    if(code!= 0)
    {
        printf("addDevice failed, code: %d\n", code);
        thmar_print_local_err();
        return -1;
    }
    char* resultJson = cJSON_Print(result);
    printf("addDevice result: %s\n", resultJson);
    /* 调用者负责释放result 内存 */ 
    cJSON_Delete(result);
    /* 释放resultStr内存 */ 
    free(resultJson);
    return 0;
}